package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.to.SkuReductionTO;
import com.atguigu.common.to.SpuBoundTO;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.to.es.SkuHasStockVo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.feign.EsFeignService;
import com.atguigu.gulimall.product.feign.WareFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.PmsSpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;


@Service("pmsSpuInfoService")
public class PmsSpuInfoServiceImpl extends ServiceImpl<PmsSpuInfoDao, PmsSpuInfoEntity> implements PmsSpuInfoService {

    @Resource
    private PmsSpuInfoDescService spuInfoDescService;
    @Resource
    private PmsSpuImagesService spuImagesService;
    @Resource
    private PmsAttrService attrService;
    @Resource
    private PmsProductAttrValueService attrValueService;
    @Resource
    private CouponFeignService couponFeignService;
    @Resource
    private PmsSkuInfoService skuInfoService;
    @Resource
    private PmsSkuImagesService skuImagesService;
    @Resource
    private PmsSkuSaleAttrValueService skuSaleAttrValueService;
    @Resource
    private PmsBrandService brandService;
    @Resource
    private PmsCategoryService categoryService;
    @Resource
    private WareFeignService wareFeignService;
    @Resource
    private EsFeignService esFeignService;
    @Resource
    private PmsSpuInfoDao pmsSpuInfoDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        /**
         * status: 0
         * key: 11
         * brandId: 2
         * catelogId: 225
         */
        QueryWrapper<PmsSpuInfoEntity> queryWrapper=new QueryWrapper<>();
        String catalogId= (String) params.get("catelogId");
        String brandId= (String) params.get("brandId");
        String key=(String) params.get("key");
        if(StringUtils.isNotBlank(key)){
            queryWrapper.and(q->{
                q.eq("spu_name",key).or().like("spu_description",key);
            });
        }
        if(params.get("status")!=null && !"".equals(params.get("status").toString())){
            Integer publishStatus=Integer.parseInt(params.get("status").toString());
            queryWrapper.eq("publish_status",publishStatus);
        }
        if(StringUtils.isNotBlank(catalogId) && !"0".equals(catalogId)) queryWrapper.eq("catalog_id",catalogId);
        if(StringUtils.isNotBlank(brandId) && !"0".equals(brandId)) queryWrapper.eq("brand_id",brandId);

        IPage<PmsSpuInfoEntity> page = this.page(
                new Query<PmsSpuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }


    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {

        // 1.保存spu基本信息 pms_sku_info
        PmsSpuInfoEntity spuInfoEntity = new PmsSpuInfoEntity();
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        BeanUtils.copyProperties(vo, spuInfoEntity);
        this.saveBatchSpuInfo(spuInfoEntity);
        // 2.保存spu的表述图片  pms_spu_info_desc
        List<String> decript = vo.getDecript();
        PmsSpuInfoDescEntity spuInfoDescEntity = new PmsSpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        // String join 的方式将它们用逗号分隔
        spuInfoDescEntity.setDecript(String.join(",", decript));
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);
        // 3.保存spu的图片集  pms_sku_images

        // 先获取所有图片
        List<String> images = vo.getImages();
        // 保存图片的时候 并且保存这个是那个spu的图片
        spuImagesService.saveImages(spuInfoEntity.getId() ,images);
        // 4.保存spu的规格属性  pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<PmsProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            PmsProductAttrValueEntity valueEntity = new PmsProductAttrValueEntity();
            valueEntity.setAttrId(attr.getAttrId());
            // 可能页面没用传入属性名字 根据属性id查到所有属性 给名字赋值
            PmsAttrEntity attrEntity = attrService.getById(attr.getAttrId());
            valueEntity.setAttrName(attrEntity.getAttrName());
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setQuickShow(attr.getShowDesc());
            valueEntity.setSpuId(spuInfoEntity.getId());

            return valueEntity;
        }).collect(Collectors.toList());
        attrValueService.saveProductAttr(collect);
        // 5.保存当前spu对应所有sku信息
        Bounds bounds = vo.getBounds();
        SpuBoundTO spuBoundTO = new SpuBoundTO();
        BeanUtils.copyProperties(bounds, spuBoundTO);
        spuBoundTO.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTO);
        if(r.getCode() != 0){
            log.error("远程保存spu积分信息失败");
        }
        // 1).spu的积分信息 sms_spu_bounds
        List<Skus> skus = vo.getSkus();
        if(skus != null && skus.size() > 0){
            // 提前查找默认图片
            skus.forEach(item -> {
                String dufaultImg = "";
                for (Images img : item.getImages()) {
                    if(img.getDefaultImg() == 1){
                        dufaultImg = img.getImgUrl();
                    }
                }
                // 2).基本信息的保存 pms_sku_info
                // skuName 、price、skuTitle、skuSubtitle 这些属性需要手动保存
                PmsSkuInfoEntity skuInfoEntity = new PmsSkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                // 设置spu的品牌id
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(dufaultImg);
                skuInfoEntity.setSaleCount((long) (Math.random()*2888));
                skuInfoService.saveSkuInfo(skuInfoEntity);

                // 3).保存sku的图片信息  pms_sku_images
                // sku保存完毕 自增主键就出来了 收集所有图片
                Long skuId = skuInfoEntity.getSkuId();
                List<PmsSkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {
                    PmsSkuImagesEntity skuImagesEntity = new PmsSkuImagesEntity();
                    skuImagesEntity.setId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity ->
                        // 返回true就会保存 返回false就会过滤
                        !StringUtils.isEmpty(entity.getImgUrl())
                ).collect(Collectors.toList());
                skuImagesService.saveBatch(imagesEntities);

                // 4).sku的销售属性  pms_sku_sale_attr_value
                List<Attr> attr = item.getAttr();
                List<PmsSkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
                    // 对拷页面传过来的三个属性
                    PmsSkuSaleAttrValueEntity skuSaleAttrValueEntity = new PmsSkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                // 5.) sku的优惠、满减、会员价格等信息  [跨库]
                SkuReductionTO skuReductionTO = new SkuReductionTO();
                BeanUtils.copyProperties(item, skuReductionTO);
                skuReductionTO.setSkuId(skuId);
                if(skuReductionTO.getFullCount() > 0 || (skuReductionTO.getFullPrice().compareTo(new BigDecimal("0")) > 0)){
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTO);
                    if(r1.getCode() != 0){
                        log.error("远程保存sku优惠信息失败");
                    }
                }
            });
        }
    }

    @Override
    public void saveBatchSpuInfo(PmsSpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public void up(Long spuId) {
        // 1 组装数据 查出当前spuId对应的所有sku信息
        List<PmsSkuInfoEntity> skuInfoList = skuInfoService.list(new QueryWrapper<PmsSkuInfoEntity>().eq("spu_id", spuId));
        // 2 封装每个sku的信息
        List<Long> skuIds=skuInfoList.stream().map(s->{
            return s.getSkuId();
        }).collect(Collectors.toList());

        // 3.查询当前sku所有可以被用来检索的规格属性
        List<PmsProductAttrValueEntity> productAttrValueList = attrValueService.list(new QueryWrapper<PmsProductAttrValueEntity>().eq("spu_id", spuId));
        List<Long> attrIds = productAttrValueList.stream().map(pmsProductAttrValueEntity -> {
            return pmsProductAttrValueEntity.getAttrId();
        }).collect(Collectors.toList());
        Set<Long> attrIdSet= new HashSet<>(attrService.selectSearchAttrIds(attrIds));
        List<SkuEsModel.Attrs> attrsList = productAttrValueList.stream().filter(pmsProductAttrValueEntity ->
                attrIdSet.contains(pmsProductAttrValueEntity.getAttrId())
        ).map(item -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs);
            return attrs;
        }).collect(Collectors.toList());
        Map<Long, Boolean> hasStockMap=null;
        //查询是否库存
        try {
            List<SkuHasStockVo> skuHasStockList = wareFeignService.getSkuHasStock(skuIds);
            hasStockMap = skuHasStockList.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        }catch (Exception e){
            log.error("库存服务调用失败: 原因{}",e);
        }
        Map<Long, Boolean> finalStockMap = hasStockMap;
        List<SkuEsModel> skuEsModelList = skuInfoList.stream().map(sku -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(sku,skuEsModel);
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());
            // TODO 1.热度评分 0
            skuEsModel.setHotScore(0L);

            // 4 设置库存
            if(finalStockMap==null){
                skuEsModel.setHasStock(true);
            }else{
                skuEsModel.setHasStock(finalStockMap.get(sku.getSkuId()));
            }

            // brandName、brandImg
            PmsBrandEntity brandEntity = brandService.getById(skuEsModel.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            // 查询分类信息
            PmsCategoryEntity categoryEntity = categoryService.getById(skuEsModel.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());
            // 保存商品的属性
            skuEsModel.setAttrs(attrsList);
            return skuEsModel;
        }).collect(Collectors.toList());
        // 5.发给ES进行保存  mall-search
        R r = esFeignService.productStatusUp(skuEsModelList);
        if(r.getCode()==0){
            // 远程调用成功
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }

    }

    @Override
    public PmsSpuInfoEntity spuInfoBySkuId(Long skuId) {
        return pmsSpuInfoDao.spuInfoBySkuId(skuId);
    }

}